from datetime import datetime

from flask import jsonify, request, session

from pojo.Announcement import Announcement
from pojo.Announcement import mysql


def get_announcements_by_query(page_num,page_size,type,title_keyword,content_keyword,start_date,end_date):

    if page_num is None:
        return {'error': '缺少 page_num 参数'}, 400
    try:
        page_num = int(page_num)
    except ValueError:
        return {'error': 'page_num 参数必须是整数'}, 400

    if page_size is None:
        return {'error': '缺少 page_size 参数'}, 400
    try:
        page_size = int(page_size)
    except ValueError:
        return jsonify({'error': 'page_size 参数必须是整数'}), 400
    print(type,title_keyword,content_keyword,start_date,end_date)


    query = Announcement.query
    if type:
        query = Announcement.query.filter(Announcement.type == type)

    if title_keyword:
        query = query.filter(Announcement.title.like(f'%{title_keyword}%'))

    if content_keyword:
        query = query.filter(Announcement.content.like(f'%{content_keyword}%'))

    if start_date and end_date:
        query = query.filter(Announcement.publish_date >= start_date, Announcement.publish_date <= end_date)
    #
    # else :
    #     return ({
    #         "status": 1,
    #         "message": "获取失败：无法找到对应的公告信息"
    #     }),400
    total = query.count()
    announcements = query.limit(page_size).offset((page_num - 1) * page_size).all()
    # print(books)
    announcement_list= []
    # 初始化一个字典来跟踪已经添加过的书名
    added_announcements = {}
    for announcement in announcements:
        if announcement.announcement_id in added_announcements:
            continue
        entitys = get_announcement(announcement.announcement_id)
        announcement_list.append({
            'announcement_id': announcement.announcement_id,
            'type': announcement.type,
            'title': announcement.title,
            'content': announcement.content,
            'publish_date': announcement.publish_date,
        })

        # 将已添加的书名记录到字典中
        added_announcements[announcement.announcement_id] = True
        entitys = []

    if not announcement_list:
        return "未查询到相关书籍"
    if announcement_list:
        response_data = {
            'total': total,
            'message': "公告信息查询成功",
            'book_list': announcement_list
        },200
        return response_data

def get_announcement(announcement_id):
        if not announcement_id:
            return ({
                "status": 1,
                "message": "缺少必须字段"
            }), 400
        # 查询公告
        announcement = Announcement.query.get(announcement_id)
        # 如果公告不存在
        if not announcement:
            return ({
                "status": 1,
                "message": "未找到公告"
            }), 404
        # 构建返回数据
        announcement_data = {
            "announcement_id": announcement_id,
            "type": announcement.type,
            "title": announcement.title,
            "content": announcement.content,
            "publish_date": announcement.publish_date,
        }
        return ({
            "status": 0,
            "message": "找到公告",
            "data": announcement_data
        }), 200

def create_announcement():
     type = request.json.get('type')
     title = request.json.get('title')
     content = request.json.get('content')
     publish_date = request.json.get('publish_date')
     if not all([type, title, content, publish_date]):
         return ({
             "status":1,
             "message":"缺少信息无法插入数据库"
         }),400
     announcement = Announcement(
         type=type,
         title=title,
         content=content,
         publish_date=publish_date,
     )
     mysql.session.add(announcement)
     mysql.session.commit()
     return ({
         "status":0,
         "message":"新增公告信息成功",
         "data": announcement.announcement_id
     }),200

def update_announcement(announcement_id):

        announcement = Announcement.query.get(announcement_id)
        if not announcement:
            return ({
                "status": 1,
                "message": "找不到指定的公告"
            }), 404

        data = request.json
        type = data.get('type')
        title_keyword = data.get('title_keyword')
        content_keyword = data.get('content_keyword')
        publish_date = data.get('publish_date')

        if type:
            announcement.type = type
        if title_keyword:
            announcement.title_keyword = title_keyword
        if content_keyword:
            announcement.content_keyword = content_keyword
        if publish_date:
            announcement.publish_date = publish_date

        mysql.session.commit()

        return ({
            "status": 0,
            "message": "更新公告信息成功",
        }), 200






def delete_announcement(announcement_id):
    announcement = Announcement.query.get(announcement_id)
    if not announcement:
        return ({
            "status": 1,
            "message": "找不到指定的公告"
        }), 404

    mysql.session.delete(announcement)
    mysql.session.commit()

    return ({
        "status": 0,
        "message": "公告信息已成功删除",
    }), 200
